from flask import Blueprint, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import timedelta
from flask_login import UserMixin, login_user, LoginManager
import pyotp
import hashlib
from server_init import app
import random
import time

md5 = hashlib.md5()
md5.update('6zPZNTtdp1Bif0r8vt0N'.encode('utf8'))
admin_username = "pingaosuoliweng"
users = {
    admin_username: generate_password_hash(md5.hexdigest()),
}

login_manager = LoginManager()
login_manager.init_app(app)
otp = pyotp.TOTP(pyotp.random_base32(), interval=60)
admin_page = Blueprint('admin_page', __name__)

# 验证码
VALID_SECONDS = 60
verify_code_list = []


@login_manager.user_loader
def user_loader(username: str):
    if username in users:
        user_model = User()
        user_model.id = username
        return user_model
    return None


class User(UserMixin):
    pass


@admin_page.route('/admin/login', methods=['POST'])
def admin_login():
    params = request.get_json()
    if 'username' not in params:
        return '缺少参数username'
    if 'password' not in params:
        return '缺少参数password'

    username = params['username']
    password = params['password']

    if username in users:
        if check_password_hash(users.get(username), password):
            user_model = User()
            user_model.id = username
            login_user(user_model)

            access_token = create_access_token(identity=username, expires_delta=False)
            return jsonify(access_token=access_token), 200

    return 'no'


# @admin_page.route("/generate-verify-code", methods=['GET'])
# @jwt_required(optional=False)
# def generate_verify_code():
#     userInfo = get_jwt_identity()
#     if userInfo != admin_username:
#         return '无权访问'
#
#     code = otp.now()
#     return code

@admin_page.route("/generate-verify-code", methods=['GET'])
@jwt_required(optional=False)
def generate_verify_code():
    user_info = get_jwt_identity()
    if user_info != admin_username:
        return '无权访问'

    code = random.randint(101010, 989898)
    code = str(code)
    now = time.time()
    verify_code_list.append({
        'code': code,
        'time': now
    })

    return code


# @admin_page.route("/login", methods=['GET'])
# def login():
#     args = request.args
#     if 'verify_code' not in args:
#         return '缺少参数verify_code'
#
#     verify_code = args['verify_code']
#     print('verify_code is {}'.format(verify_code))
#     result = otp.verify(verify_code)
#     if result:
#         access_token = create_access_token(identity='temp_user', expires_delta=timedelta(hours=8))
#         return jsonify(access_token=access_token), 200
#     else:
#         return 'no'


@admin_page.route("/login", methods=['GET'])
def login():
    args = request.args
    if 'verify_code' not in args:
        return '缺少参数verify_code'

    verify_code = args['verify_code']
    print('verify_code is {}'.format(verify_code))

    # 清除过期验证码,保留有效期验证码
    global verify_code_list
    valid_list = []
    now = time.time()
    for code in verify_code_list:
        if now - code['time'] < VALID_SECONDS:
            valid_list.append(code)
    verify_code_list = valid_list

    # 判断验证码是否有效
    result = False
    for code in verify_code_list:
        if code['code'] == verify_code:
            result = True

    if result:
        access_token = create_access_token(identity='temp_user', expires_delta=timedelta(hours=8))
        return jsonify(access_token=access_token), 200
    else:
        return 'no'
